package finalproject.mobapp.Main;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import finalproject.mobapp.R;
import finalproject.mobapp.HttpRequestController.CustomHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddPoiActivity extends Activity {
	public static final String PREF_NAME = "SHARED_PREFERENCES";
	public static SharedPreferences prefs;
	Context context = this;
	
	EditText et_title;
	EditText et_description;
	Spinner spinner_category;
	TextView tv_location;
	
	int user_id;
	String title;
	String description;
	String category_selected = null;
	double latitude = 0;
	double longitude = 0;
	
	LocationManager locationManager;
	boolean gps_enabled = false;
    boolean network_enabled = false;
    Timer timer1;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addpoi);
        
        prefs = this.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        user_id = prefs.getInt("user_id", 0);
        
        et_title = (EditText) findViewById(R.id.title);       
        et_description = (EditText) findViewById(R.id.description);
        
        List<String> category_list = new ArrayList<String>();
        String response = null;
        try {
			response = CustomHttpClient.executeHttpGet(CustomHttpClient.BASE_URL + "getAllCategories");
			
			JSONArray jArray = new JSONArray(response);
			JSONObject json_data = null;
			for (int i=0; i<jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				String cat_name = json_data.getString("name");
				category_list.add(cat_name);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        spinner_category = (Spinner) findViewById(R.id.category_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, category_list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_category.setAdapter(adapter);
        spinner_category.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        tv_location = (TextView) findViewById(R.id.location);
    }
    
    public void retrieveLocationHandle(View v) {
    	gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    	network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    	
    	if (gps_enabled) {
    		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
    	}
    	
    	timer1 = new Timer();
    	timer1.schedule(new GetLastLocation(), 30000);
    }
    
    LocationListener locationListenerGps = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {
			timer1.cancel();
			if (location != null) {
	    		latitude = location.getLatitude();
	    		longitude = location.getLongitude();
	    	}
			tv_location.setText("Latitude : " + String.valueOf(latitude) + "\nLongitude : " + String.valueOf(longitude));
			locationManager.removeUpdates(locationListenerGps);
		}

		@Override
		public void onProviderDisabled(String provider) {}

		@Override
		public void onProviderEnabled(String provider) {}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {}
    	
    };
    
    class GetLastLocation extends TimerTask {
		@Override
		public void run() {
			//AddPoiActivity.this.findViewById(R.id.location).post(new Runnable() {
			tv_location.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					locationManager.removeUpdates(locationListenerGps);
					
					Location gps_loc = null;
		    		Location net_loc = null;
		    		
		    		if (gps_enabled) {
		    			gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		    		}
		    		if (network_enabled) {
		    			net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		    		}
		    		
		    		if(gps_loc!=null && net_loc!=null){
		                if(gps_loc.getTime()>net_loc.getTime()) {
		                	Location location = gps_loc;
		                	latitude = location.getLatitude();
		    	    		longitude = location.getLongitude();
		                } else {
		                	Location location = net_loc;
		                	latitude = location.getLatitude();
		    	    		longitude = location.getLongitude();
		                }
		            } else if (gps_loc != null) {
		    			Location location = gps_loc;
		    			latitude = location.getLatitude();
			    		longitude = location.getLongitude();
		    		} else if (net_loc != null) {
		    			Location location = net_loc;
		    			latitude = location.getLatitude();
			    		longitude = location.getLongitude();
		    		}
		    		tv_location.setText("Latitude : " + String.valueOf(latitude) + "\nLongitude : " + String.valueOf(longitude));
				}
			});
		}
    }
    
    public void addPoiHandle(View v) {
    	title = et_title.getText().toString();
    	description = et_description.getText().toString();
    	
    	ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    	postParameters.add(new BasicNameValuePair("user_id", String.valueOf(user_id)));
    	postParameters.add(new BasicNameValuePair("title", title));
    	postParameters.add(new BasicNameValuePair("description", description));
    	postParameters.add(new BasicNameValuePair("category", category_selected));
    	postParameters.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
    	postParameters.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
    	
    	String response = null;
    	String poiList = "";
    	try {
			response = CustomHttpClient.executeHttpPost(CustomHttpClient.BASE_URL + "addPoi", postParameters);
			String res = response.toString();
			res.replaceAll("\\s", "");
			if (res.equals("0") || res.equals("1")) {
				if (res.equals("0")) {
					Toast.makeText(getApplicationContext(), "Add POI failed", Toast.LENGTH_LONG).show();
				} else if (res.equals("1")) {
					Toast.makeText(getApplicationContext(), "Add POI succeed", Toast.LENGTH_LONG).show();
					
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), MenuActivity.class);
					
					AddPoiActivity.this.finish();
					startActivity(intent);
				}
			} else {
				JSONArray jArray = new JSONArray(response);
				JSONObject json_data = null;
				for (int i=0; i<jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String poi_title = json_data.getString("title");
					poiList += poi_title + "\n";
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage("Suspicious POI found. Is your POI included in this list?\n" + poiList)
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					AddPoiActivity.this.finish();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			    	postParameters.add(new BasicNameValuePair("user_id", String.valueOf(user_id)));
			    	postParameters.add(new BasicNameValuePair("title", title));
			    	postParameters.add(new BasicNameValuePair("description", description));
			    	postParameters.add(new BasicNameValuePair("category", category_selected));
			    	postParameters.add(new BasicNameValuePair("latitude", String.valueOf(latitude)));
			    	postParameters.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
			    	
			    	String response = null;
			    	try {
						response = CustomHttpClient.executeHttpPost(CustomHttpClient.BASE_URL + "verifyAddPoi", postParameters);
						String res = response.toString();
						res.replaceAll("\\s", "");
						
						if (res.equals("0")) {
							Toast.makeText(getApplicationContext(), "Add POI failed", Toast.LENGTH_LONG).show();
						} else if (res.equals("1")) {
							Toast.makeText(getApplicationContext(), "Add POI succeed", Toast.LENGTH_LONG).show();
							
							Intent intent = new Intent();
							intent.setClass(getApplicationContext(), MenuActivity.class);
							
							AddPoiActivity.this.finish();
							startActivity(intent);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		AlertDialog alert = builder.create();
		alert.show();
    }
    
    public void backHandle(View v) {
    	//Intent intent = new Intent();
		//intent.setClass(getApplicationContext(), MenuActivity.class);
		
		AddPoiActivity.this.finish();
		//startActivity(intent);
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View v, int pos,
				long id) {
			// TODO Auto-generated method stub
			category_selected = parent.getItemAtPosition(pos).toString();
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
			
		}
    }
}
